package com.rf.richfitwheel.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.springframework.util.Base64Utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * pdf util
 * @author
 */
public class PdfUtil {

    /**
     * 合并多个pdf文件到指定文件
     * @param files
     * @param newFile
     * @return
     */
    public static boolean mergePdfs(File[] files, String newFile) {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(files[0].getPath()).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[0].getPath());
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != document) {
                document.close();
            }
        }
        return retValue;
    }

    /**
     * 合并PDF到指定文件
     * @param fileOutputStream
     * @param newFile
     * @return
     * @throws Exception
     */
    public static boolean mergePdfs(List<ByteArrayOutputStream> fileOutputStream, String newFile) throws Exception {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(fileOutputStream.get(0).toByteArray()).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
            document.open();
            for (int i = 0; i < fileOutputStream.size(); i++) {
                PdfReader reader = new PdfReader(fileOutputStream.get(i).toByteArray());
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != document) {
                document.close();
            }
        }
        return retValue;
    }

    /**
     * 合并PDF 返回base64
     * @param fileOutputStream
     * @param newFile
     * @return
     * @throws Exception
     */
    public static String mergePdfsToBase64(List<ByteArrayOutputStream> fileOutputStream, String newFile) throws Exception {
        try {
            mergePdfs(fileOutputStream, newFile);
            return fileToBase64(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            delFile(newFile);
        }
    }

    /**
     * 删除文件
     * @param filePath
     */
    public static void delFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * fileToBase64
     * @param filePath
     * @return
     */
    public static String fileToBase64(String filePath) {
        byte[] data = null;
        try {
            InputStream in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64Utils.encodeToString(data);
    }

    /**
     * fileToBytes
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[]  fileToBytes(File file) throws IOException {
        FileInputStream fis=null;
        ByteArrayOutputStream bos = null;
        byte[] resultBytes=null;
        try {
            fis=new FileInputStream(file);
            bos=new ByteArrayOutputStream();
            byte[] bytes=new byte[1024];
            int len;
            while((len=fis.read(bytes))!=-1){
                bos.write(bytes,0,len);
            }
            resultBytes = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bos.close();
            fis.close();
        }
        return  resultBytes;
    }

    public static void main(String[] args) throws Exception {
        File file1 = new File("D:\\B20230701050011.pdf");
        File file2 = new File("D:\\B202307011800412.pdf");
        ArrayList<File> files = new ArrayList<File>() {{
            add(file1);
            add(file2);
        }};
        List<ByteArrayOutputStream> collect = files.stream().map(file -> {
            FileInputStream fileInputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                outputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = fileInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return outputStream;
        }).collect(Collectors.toList());
//        mergePdfs(files, "D:\\merge.pdf");
        mergePdfs(collect, "D:\\merge.pdf");
    }

}
